
const Base64 = require('./Base64.js');

require('./hmac.js');
require('./sha1.js');
const Crypto = require('./crypto.js');

//上传图片配置参数
class OssUploadConfig {
  constructor(upload_url, access_key_id, access_key_secret, security_token) {
    this.upload_url = upload_url
    this.access_key_id = access_key_id
    this.access_key_secret = access_key_secret
    this.security_token = security_token
    this.timeout = 87600
  }
}


/*
  调用示例：
        const tempFilePaths = files.tempFilePaths
      const env = new OssUploadConfig("https://wangjun-test-bucket.oss-cn-beijing.aliyuncs.com", "STS.NTWqJvgjTYcQGM95VQN9oVxtn", "CopEcVs2msc98azRMkR5GBAK6CLG8vgjTDqtvZTVocpZ", "CAIS9gF1q6Ft5B2yfSjIr5fiOvDCirV17qG6RWuI0VYEQrZDub3fjDz2IH5JeHdhCO0Ztfwzm29T7PkTlqRuUJJfHBafMZYuscQGqatZ3XVA/Z7b16cNrbH4M0rxYkeJ8a2/SuH9S8ynCZXJQlvYlyh17KLnfDG5JTKMOoGIjpgVBbZ+HHPPD1x8CcxROxFppeIDKHLVLozNCBPxhXfKB0ca0WgVy0EHsP/mmpDHtUuO1AWrk7RL/r6ceMb0M5NeW75kSMqw0eBMca7M7TVd8RAi9t0t0vEYp2aW447GWwUOvE7cbLvOkMdmKQhifbQ3ALJUJScGS0Pte4YagAFlZsmuULl6J1jEsKtIhCBkbsg1j9vb/bg4E/WwtdeqFQnocklminHpsTBEDGY0sMlIXRQ4dx7wwce51gITUElQK2ew3wm9rX2ye25s8fEmc+ZejEQctnGW9TK4Ss2xvgOHY/QF1cJdHDzmd3l5+Ps0tRaZDvvem73mHvp7Anogyg==")
      UploadOssFile(env, {
        filePath: tempFilePaths[0],
        dir: "test/",
        success: function (res) {
          console.log("rrrrrrrrrrrrrrrrrrrrrrrrrrrrrr上传成功", res)
        },
        fail: function (res) {
          console.log("rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr上传失败", res)
        }
      })

*/
const UploadOssFile = function (env, params) {
  if (!(env instanceof OssUploadConfig)) {
    console.log('env is not right ,upload file failed!')
  }
  if (!params.filePath || params.filePath.length < 9) {
    wx.showModal({
      title: '图片错误',
      content: '请重试',
      showCancel: false,
    })
    return;
  }
  const aliyunFileKey = params.dir + params.filePath.replace('wxfile://', '');

  const aliyunServerURL = env.upload_url;
  const accessid = env.access_key_id;
  const policyBase64 = getPolicyBase64(env.timeout);
  const signature = getSignature(policyBase64, env.access_key_secret);

  console.log('signature:', signature)
  wx.uploadFile({
    url: aliyunServerURL, 
    filePath: params.filePath,
    name: 'file',
    formData: {
      'key': aliyunFileKey,
      'policy': policyBase64,
      'OSSAccessKeyId': accessid,
      'signature': signature,
      'success_action_status': '200',
      'x-oss-security-token': env.security_token,
    },
    success: function (res) {
      if (res.statusCode != 200) {
        if(params.fail){
          params.fail(res)
        }
        return;
      }
      if(params.success){
        params.success(aliyunFileKey);
      }
    },
    fail: function (err) {
      err.wxaddinfo = aliyunServerURL;
      if (params.fail) {
        params.fail(err)
      }
    },
  })
}

const getPolicyBase64 = function (timeout) {
  let date = new Date();
  date.setHours(date.getHours() + timeout);
  let srcT = date.toISOString();
  console.log('srcT:', srcT)
  const policyText = {
    "expiration": srcT, //设置该Policy的失效时间
    "conditions": [
      ["content-length-range", 0, 5 * 1024 * 1024] // 设置上传文件的大小限制,5mb
    ]
  };

  const policyBase64 = Base64.encode(JSON.stringify(policyText));
  return policyBase64;
}

const getSignature = function (policyBase64, access_key_secret) {
  const accesskey = access_key_secret;

  const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, {
    asBytes: true
  });
  const signature = Crypto.util.bytesToBase64(bytes);

  return signature;
}

module.exports = {
  UploadOssFile,
  OssUploadConfig
};